package com.wechat.utils.kit;

import org.apache.commons.codec.binary.Base64;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * Created by MrWang on 2016/5/23.
 */
public class CookieKit {
    /**
     * 设置cookie有效期，根据需要自定义[本系统设置为30天]
     */
    private final static Integer COOKIE_MAX_AGE = 60 * 60 * 24 *365;

    public final static  Integer COOKIE_MAX_AGE_DAY=24*60*60;
    public final static  Integer COOKIE_MAX_AGE_MONTH=COOKIE_MAX_AGE_DAY*30;
    public final static  Integer COOKIE_MAX_AGE_YEAR=COOKIE_MAX_AGE_MONTH*12;

    private final static String ENTRYSALT="WUsxdxR*^7^*%%";//base64加密解密盐
    /**
     *
     * @desc 添加一条新的Cookie信息，可以设置其最长有效时间(单位：秒)
     * @param response
     * @param name
     * @param value
     * @param maxAge
     */
    public static void setCookie(HttpServletResponse response, String name, String value, int maxAge)
    {
        if (value == null)
            value = "";
        Cookie cookie = new Cookie(name, value);
        if(maxAge!=0){
            cookie.setMaxAge(maxAge);
        }else{
//            cookie.setMaxAge(Math.abs(COOKIE_MAX_AGE));
            cookie.setMaxAge(COOKIE_MAX_AGE_YEAR);
        }
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public static void  setCookie(HttpServletResponse response, String name, String value, int maxAge,String domain){
        if (value == null)
            value = "";
        Cookie cookie = new Cookie(name, value);
        if(maxAge!=0){
            cookie.setMaxAge(maxAge);
        }else{
//            cookie.setMaxAge(Math.abs(COOKIE_MAX_AGE));
            cookie.setMaxAge(COOKIE_MAX_AGE_YEAR);
        }
        cookie.setPath("/");
        cookie.setDomain(domain);
        response.addCookie(cookie);
    }

    public static void removeCookie(HttpServletResponse response,String name){
        Cookie cookie = new Cookie(name, "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }


    /**
     *
     * @desc 根据Cookie名称得到Cookie的值，没有返回Null
     * @param request
     * @param name
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String name)
    {
        Cookie cookie = getCookie(request, name);
        if (cookie != null)
        {
            return cookie.getValue();
        }
        else
        {
            return null;
        }
    }
    /**
     *
     * @desc 根据Cookie名称得到Cookie对象，不存在该对象则返回Null
     * @param request
     * @param name
     */
    public static Cookie getCookie(HttpServletRequest request, String name)
    {
        Cookie cookies[] = request.getCookies();
        if (cookies == null || name == null || name.length() == 0)
            return null;
        Cookie cookie = null;
        for (int i = 0; i < cookies.length; i++)
        {
            if (!cookies[i].getName().equals(name))
                continue;
            cookie = cookies[i];
            if (request.getServerName().equals(cookie.getDomain()))
                break;
        }

        return cookie;
    }


    /**
     * 编码
     * @param cookieStr
     * @return
     */
    public static String encodeBase64(String cookieStr){

        try {
            cookieStr+=ENTRYSALT;
            cookieStr = new String(Base64.encodeBase64(cookieStr.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return cookieStr;
    }

    /**
     * 解码
     * @param cookieStr
     * @return
     */
    public static String decodeBase64(String cookieStr){
        try {
            cookieStr = new String(Base64.decodeBase64(cookieStr.getBytes()), "UTF-8");
            cookieStr=cookieStr.replace(ENTRYSALT,"");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return cookieStr;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "ffdd订单";
        String decode = new String(Base64.encodeBase64(str.getBytes()));
        System.out.println("eee" + decode);

        String ddd = new String(Base64.decodeBase64(decode));
        System.out.println("" + ddd);
    }
}
